import 'dart:async';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_permission_mixin.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/backend_service.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_polling_timer_helper.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_service.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/service/guest_service.dart';
import 'package:inmotion_pro/service/launch_service.dart';
import 'package:lx_widgets_library/alert/loading.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../../service/cache_config_service.dart';
import '../mixin/realtime_info_mixin.dart';
import 'helper.dart';
import 'state.dart';

class VehicleController extends GetxController
    with
        CacheMixin,
        RealtimeInfoMixin,
        BluetoothMixin,
        BluetoothPermissionMixin,
        VehicleTypeMixin,
        HttpRequestMixin {
  // 状态
  final VehicleState state = VehicleState();

  // 帮助类
  final MainHelper helper = MainHelper();

  // 蓝牙权限监听
  StreamSubscription<CustomBluetoothAdapterState>?
      _bluetoothPermissionSubscription;

  // 当前车辆类型
  VehicleType get _vehicleType => GlobalService.to.currentVehicleType;

  // 首页页面需要轮询的实时数据类型列表
  List<(PollingTimerType, int)> get _vehicleHomePagePollingTypes =>
      RealtimeDataPollingTimeHelper.vehicleHomePagePollingTypes;

  @override
  void onInit() {
    super.onInit();

    // 监听蓝牙状态（state.bluetoothConnectState状态有响应逻辑处理，而VechileConnectionService.to.bluetoothConnectState是瞬间状态）
    VechileConnectionService.to.bluetoothConnectState.listen((event) async {
      debugPrint("蓝牙状态: $event");

      switch (event) {
        case CustomBluetoothConnectState.connected:
          // 蓝牙已连接
          debugPrint("✅ 当前MTU: ${await VechileConnectionService.to.mtu}");
          // 因为设备连接成功，不仅蓝牙连接成功，还需要获取设备基础信息完成
          // 所以成功的状态【state.bluetoothConnectState.value = .connected】由业务逻辑中函数自行处理
          break;
        case CustomBluetoothConnectState.disconnected:
          state.bluetoothConnectState.value = event;
          // 被动蓝牙断开连接
          _bluetoothDisconnectDropped();
          break;
        default:
          state.bluetoothConnectState.value = event;
          break;
      }
    });

    // 刷新数据
    refreshData();
  }

  @override
  Future<void> onClose() async {
    // 退出游客模式
    await GuestService.to.leaveGuestMode();
    super.onClose();
    // 停止扫描
    _bluetoothStopScan();
  }

  // 刷新页面数据
  refreshData() async {
    if (GlobalService.to.isLoggedIn) {
      // 缓存的车辆列表
      final cacheVehicleList = GlobalService.to.cacheVehicleList.toList();
      // 缓存的车辆列表不为空时
      if (cacheVehicleList.isNotEmpty) {
        // 搜索并连接目标设备
        _searchAndConnectTargetDevice();
        // 获取缓存车辆实时数据
        _getCacheVehicleRealTimeData();
      }
      // 更新车辆功能按钮列表
      _updateVehicleFunctionButtons();
      // 监听车辆Flash中最新的单次统计数据
      _listenFlashLatestVehicleStatisticsOnce();

      // 获取服务端最新的车辆列表数据，更新本地缓存
      LaunchService.to.checkAuthorizedVehicle().then((hasWait) {
        if (hasWait) refreshData();
      }).catchErrorHandler();
    } else {
      // 游客模式
      _setGuestModeData();
    }
  }

  // 设置游客模式数据
  _setGuestModeData() async {
    state.bluetoothConnectState.value = CustomBluetoothConnectState.connected;
    state.currentBatteryLevel.value = 0.99;
    state.currentRemainingMileage.value = 70;
    state.totalMileage.value = 110;
    state.isLocked.value = false;
    // 更新车辆功能按钮列表
    _updateVehicleFunctionButtons();
  }

  // 搜索并连接目标设备
  _searchAndConnectTargetDevice() async {
    // 连接失败后的处理函数
    failed() {
      state.bluetoothConnectState.value =
          CustomBluetoothConnectState.disconnected;
    }

    final vehicleModel = GlobalService.to.currentVehicleModel.value;
    if (VechileConnectionService.to.connectedDevice != null) {
      if (VechileConnectionService.to.connectedDevice!.bleName ==
          vehicleModel.bleName) {
        // 当搜索页连接成功时，会进入这里
        debugPrint("✅ ${vehicleModel.bleName}【已连接】");
        // 连接完成, 开始实时数据轮询
        _bluetoothConnectedComplete();
        return;
      } else {
        // 主动断开当前连接的车辆
        _activelyDisconnectBluetooth();
      }
    }
    // 检测蓝牙权限
    _bluetoothPermissionSubscription = bluetoothPermissionBluetoothPermission(
      onSuccess: () {
        state.bluetoothConnectState.value =
            CustomBluetoothConnectState.connecting;
        // 搜索并连接车辆
        bluetoothMixinSearchAndConnectTargetDevice(
          GlobalService.to.currentVehicleModel.value.bleName,
          searchOnTimeout: () {
            // 搜索超时
            Loading.showError(local.ble_search_timeout);
            failed();
          },
          connectOnTimeout: () {
            // 连接超时
            Loading.showError(local.ble_connect_timeout);
            failed();
          },
        ).then((connectSuccess) async {
          if (connectSuccess) {
            // 连接完成, 开始实时数据轮询
            _bluetoothConnectedComplete();
          } else {
            Loading.showToast(local.ble_connect_failed);
            failed();
          }
        }).catchErrorHandler(
          onError: (p0) {
            failed();
          },
        );
      },
      onFailed: () {
        _bluetoothStopScan();
      },
    );
  }

  // 完成蓝牙连接，开始循环获取车辆实时数据
  _bluetoothConnectedComplete() {
    debugPrint("✅ 已获取设备基础信息，完成蓝牙连接");
    Loading.showSuccess(local.ble_connect_success);
    state.bluetoothConnectState.value = CustomBluetoothConnectState.connected;
    // 开始循环获取车辆实时数据
    startLoopToGetVehicleRealTimeData();
  }

  // 开始循环获取车辆实时数据
  startLoopToGetVehicleRealTimeData() {
    // 实时数据轮询
    realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
      pollingTypes: _vehicleHomePagePollingTypes,
      realtimeInfoCallback: (p0) {
        // 当前电量
        state.currentBatteryLevel.value = p0.batteryPercentage;
        // 当前剩余里程
        state.currentRemainingMileage.value = p0.estimatedRemainingMileage;
        // 刷新缓存中的车辆实时数据
        helper.refreshCacheVehicleRealTimeData(
          GlobalService.to.currentVehicleModel.value.bleName,
          estimatedRemainingMileage: p0.estimatedRemainingMileage,
          batteryPercent: p0.batteryPercentage,
        );
        // 云盒信号强度
        state.tboxSignalLevel.value = p0.signalStrength;
      },
      realtimeStatusCallback: (p0) {
        // 锁车状态
        state.isLocked.value = p0.isHmicRunModeLocked;
        state.lightType.value = _vehicleType.getLightType(p0.isLampOn);
        // 更新车辆功能按钮列表
        _updateVehicleFunctionButtons();
      },
      realtimeErrorCallback: (p0) {
        // 实时错误数据回调
        state.warningMsgList.value = p0.vehicleErrors;
      },
      statisticsTotalCallback: (p0) {
        // 统计总数据回调
        state.totalMileage.value = p0.totalMileage;
        // 刷新缓存中的车辆实时数据
        helper.refreshCacheVehicleRealTimeData(
          GlobalService.to.currentVehicleModel.value.bleName,
          totalMileage: p0.totalMileage,
        );
      },
    ).then((loopSuccess) {
      if (loopSuccess) {
        helper.afterConnectSuccessBusinessProcess();
      } else {
        _activelyDisconnectBluetooth();
      }
    }).catchErrorHandler();
  }

  // 切换车辆
  switchVehicleOnTap() async {
    final vehicleList = GlobalService.to.cacheVehicleList.toList();
    vehicleList.sort((a, b) => a.isSelected ? -1 : 1);
    helper.switchVehicle(
      disconnectAndSearchCallback: () {
        searchVehicleOnTap();
      },
      changeVehicleCallback: (model) {
        if (GlobalService.to.isLoggedIn) {
          refreshData();
        } else {
          _setGuestModeData();
        }
      },
    );
  }

  // 蓝牙连接/断开事件
  bluetoothConnectOnTap() {
    helper.bluetoothConnectOrDisconnect(
      bluetoothConnectState: state.bluetoothConnectState.value,
      bluetoothConnectStateCallback: (p0) {
        // 只有游客模式下，才会通过此回调更新state.bluetoothConnectState
        state.bluetoothConnectState.value = p0;
      },
      connectVehicleCallback: () async {
        // 搜索并连接目标设备
        _searchAndConnectTargetDevice();
      },
      disconnectVehicleCallback: () async {
        // 主动断开蓝牙连接
        _activelyDisconnectBluetooth();
      },
    );
  }

  // 车辆设置
  vehicleSettingOnTap() async {
    if (!_vehicleConnected) return;
    realtimeInfoMixinNavigatorToNamed(AppRoutes.VEHICLE_SETTING,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 更多功能
  moreFunctionOnTap() {
    realtimeInfoMixinNavigatorToNamed(AppRoutes.VEHICLE_MORE_FEATURES,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 实时详情
  realtimeDetailOnTap() {
    if (!_vehicleConnected) return;
    realtimeInfoMixinNavigatorToNamed(AppRoutes.VEHICLE_REALTIME_DETAIL,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 4G按钮事件
  button4GOnTap() {}

  // 按喇叭事件
  hornOnTap() {
    if (!_vehicleConnected) return;
    helper.clickHorn(_vehicleHomePagePollingTypes);
  }

  // 锁车/解锁事件
  lockVehicleOnTap() {
    if (!_vehicleConnected) return;
    lock() {
      helper.lockVehicle(
        state.isLocked.value,
        _vehicleHomePagePollingTypes,
        (p0) {
          state.isLocked.value = p0;
          _updateVehicleFunctionButtons();
        },
      );
    }

    if (GlobalService.to.isLoggedIn) {
      Loading.showLoading(local.establishing_secure_connection);
      // 建立安全连接
      helper.buildSafeConnection().then((isSafeConnection) {
        if (isSafeConnection) {
          lock();
        } else {
          Loading.showError(local.failed_to_establish_a_secure_connection);
        }
      }).catchErrorHandler();
    } else {
      // 游客模式直接锁车/解锁
      lock();
    }
  }

  // 灯光事件
  lightOnTap() {
    if (!_vehicleConnected) return;
    var val = _vehicleType.getNextLightValue(state.lightType.value);
    helper.clickLight(
      _vehicleHomePagePollingTypes,
      lowBeam: val.$1,
      highBeam: val.$2,
    );
  }

  // 查看错误警告信息
  warningOnTap() {
    if (!_vehicleConnected) return;
    realtimeInfoMixinNavigatorToNamed(AppRoutes.VEHICLE_ERROR,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 骑行记录
  cyclingRecordOnTap() {
    realtimeInfoMixinNavigatorToNamed(AppRoutes.CYCLING_RECORD_LIST,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 申请车主
  goAuthOwnerOnTap() {
    helper.applyOwner();
  }

  // 搜索车辆
  // 1.没有缓存车辆
  // 2.重新搜索车辆
  searchVehicleOnTap() {
    AppBackendService.to
        .stop()
        .then((_) => realtimeInfoMixinStopLoopToGetVehicleRealTimeData())
        .then((_) => _activelyDisconnectBluetooth().then((_) =>
            Get.toNamed(AppRoutes.SEARCH_VEHICLE)
                ?.then((value) => refreshData())))
        .catchErrorHandler();
  }

  // 判断车辆是否已连接蓝牙或云盒
  bool get _vehicleConnected {
    if (state.bluetoothConnectState.value ==
            CustomBluetoothConnectState.connected ||
        GlobalService.to.currentVehicleModel.value.hmicStatus) {
      return true;
    }
    Loading.showToast(local.your_vehicle_is_disconnected);
    return false;
  }

  // 更新车辆功能按钮列表
  _updateVehicleFunctionButtons() {
    state.getVehicleFunctionButtons.value =
        _vehicleType.getVehicleFunctionButtonList(
      isLocked: state.isLocked.value,
      lightType: state.lightType.value,
    );
  }

  // 获取缓存中的车辆实时数据（电量、预估剩余里程、总里程）
  _getCacheVehicleRealTimeData() {
    cacheMixinGetCacheVehicleRealtimeData(
            GlobalService.to.currentVehicleModel.value.bleName)
        .then((realtimeData) {
      if (realtimeData != null) {
        state.currentBatteryLevel.value = realtimeData.batteryPercentage ?? 0.0;
        state.currentRemainingMileage.value =
            realtimeData.estimatedRemainingMileage ?? 0.0;
        state.totalMileage.value = realtimeData.totalMileage ?? 0.0;
        state.flashLatestCyclingRecord.value = realtimeData.cyclingRecord;
      }
    });
  }

  // 监听实时获取车辆Flash中最新的单次统计数据
  void _listenFlashLatestVehicleStatisticsOnce() {
    helper.statisticsOnceCallback = (p0) {
      // 会在MainHelper的afterConnectSuccessBusinessProcess中调用一次
      state.flashLatestCyclingRecord.value = p0;
      // 刷新缓存中的车辆实时数据
      helper.refreshCacheVehicleRealTimeData(
        GlobalService.to.currentVehicleModel.value.bleName,
        cyclingRecord: p0.toMap(),
      );
    };
  }

  // 主动断开蓝牙连接
  Future<void> _activelyDisconnectBluetooth() {
    state.bluetoothConnectState.value =
        CustomBluetoothConnectState.disconnected;
    // 主动断开蓝牙连接
    return bluetoothMixinDisconnect().catchErrorHandler();
  }

  // 蓝牙断开连接后的处理，非主动断开连接
  _bluetoothDisconnectDropped() {
    Future.wait([
      // 停止实时数据轮询
      realtimeInfoMixinStopLoopToGetVehicleRealTimeData(),
      // 安全连接 --> false
      CacheConfigService.to.setSecureConnection(false),
    ]).catchErrorHandler();
  }

  // 停止扫描
  _bluetoothStopScan() {
    bluetoothMixinStopScan();
    _bluetoothPermissionSubscription?.cancel();
  }
}
